package com.lg.partition27;

import java.io.*;
import java.util.Arrays;

/**
 * https://www.luogu.com.cn/blog/NewWorldUNknown/p2661-xin-xi-zhuan-di-exp
 * @author `RKC`
 * @date 2022/4/21 17:51
 */
public class P2661NOIP2015提高组_信息传递_并查集 {

    private static final int N = 200010;
    private static int[] parent = new int[N], dist = new int[N];
    private static int n;

    private static StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    private static PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException {
        n = nextInt();
        for (int i = 1; i <= n; i++) parent[i] = i;
        int ans = 0x3f3f3f3f;
        for (int i = 1; i <= n; i++) {
            int j = nextInt();
            int x = find(i), y = find(j);
            if (x != y) {
                parent[x] = y;
                dist[i] = dist[j] + 1;
            } else {
                ans = Math.min(ans, dist[i] + dist[j] + 1);
            }
        }
        writer.println(ans);
        writer.flush();
    }

    private static int find(int x) {
        if (x != parent[x]) {
            int last = parent[x];
            parent[x] = find(parent[x]);
            dist[x] += dist[last];
        }
        return parent[x];
    }

    private static int nextInt() throws IOException {
        tokenizer.nextToken();
        return (int) tokenizer.nval;
    }
}
